package com.bhs.sansonglogistics.ui.order;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.dialog.AttachMoreDialog2;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MediaStoreUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.utils.WxShareUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.journeyapps.barcodescanner.ScanContract;
import com.journeyapps.barcodescanner.ScanOptions;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import zpSDK.zpSDK.zpBluetoothPrinter;

/**
 * 扫一扫发货取货
 */
public class ScanCodeDeliveryActivity extends BaseActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {

    private LinearLayout mLlTab;
    private TextView mTvInvitationCode;
    private TextView mTvSpecialCode;
    private TextView mTvHint;
    private TextView mTvTitle;
    private TextView mTvCompanyName;
    private FrameLayout mFlCode;
    private String company_name;
    private String content;
    public static BluetoothAdapter myBluetoothAdapter;
    private Bitmap bmp;
    private String bluetoothAddress;
    private TextView mTvMore;
    private int type;
    private List<String> mList=new ArrayList<>();

    @Override
    public int initLayout() {
        return R.layout.activity_scan_code_delivery;
    }

    @Override
    public void initView() {
        type = getIntent().getIntExtra("type", 0);
        findViewById(R.id.tv_save).setOnClickListener(this);
        findViewById(R.id.tv_share).setOnClickListener(this);
        findViewById(R.id.fl_scan).setOnClickListener(this);
        mTvCompanyName = findViewById(R.id.tv_company_name);
        company_name = SharedPreferencesUtils.getString(mActivity, "company_name");
        mTvCompanyName.setText(company_name);
        mLlTab = findViewById(R.id.ll_tab);
        mTvInvitationCode = findViewById(R.id.tv_Invitation_code);
        mTvInvitationCode.setOnClickListener(this);
        mTvSpecialCode = findViewById(R.id.tv_special_code);
        mTvSpecialCode.setOnClickListener(this);
        mTvHint = findViewById(R.id.tv_hint);
        mTvTitle = findViewById(R.id.tv_title);
        mFlCode = findViewById(R.id.fl_code);
        content = getIntent().getStringExtra("url");
        mTvMore = findViewById(R.id.tv_more);
        mTvMore.setOnClickListener(this);
        //bmp=BitmapFactory.decodeResource(getResources(),R.mipmap.ic_collect);
//        Resources res=getResources();
//        InputStream is=res.openRawResource(R.mipmap.ic_collect);
//        BitmapDrawable bmpDraw=new BitmapDrawable(is);
//         bmp=bmpDraw.getBitmap();
        bluetoothAddress = SharedPreferencesUtils.getString(mActivity, "bluetoothAddress");
    }

    @Override
    public void initData() {
        mList.add("打印标签");
        mList.add("配置打印机");
        ImageView imageViewQrCode = findViewById(R.id.qrCode);
        imageViewQrCode.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= 16) {
                    imageViewQrCode.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    imageViewQrCode.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                try {
                    BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
                    //HashMap设置二维码参数
                    Map map = new HashMap();
                    //   设置容错率 L>M>Q>H  等级越高扫描时间越长,准确率越高
                    map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                    //设置外边距
                    map.put(EncodeHintType.MARGIN, 1);
                    Bitmap bitmap = barcodeEncoder.encodeBitmap(content, BarcodeFormat.QR_CODE, imageViewQrCode.getWidth(), imageViewQrCode.getHeight(), map);
                    imageViewQrCode.setImageBitmap(bitmap);
                } catch (Exception e) {

                }
            }
        });

        if (type == 1) {
            mLlTab.setVisibility(View.INVISIBLE);
        } else {
            mTvTitle.setText("");
            String invite_code = SharedPreferencesUtils.getString(mActivity, "invite_code");
//            mTvHint.setText(String.format("邀请码：%s", invite_code));
//            mTvHint.setTextColor(Color.parseColor("#485EF4"));
            mTvHint.setText("扫一下注册下载");
            mTvMore.setVisibility(View.GONE);
            Spanned PageView = Html.fromHtml("推荐下载并成功认证，可<font color=\"#FF6067\">" + "领取红包" + "</font>");
            mTvCompanyName.setText(PageView);
            mTvCompanyName.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        }
        if ((myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()) == null) {
            Toast.makeText(this, "没有找到蓝牙适配器", Toast.LENGTH_LONG).show();
        }

    }

    // Register the launcher and result handler
    private final ActivityResultLauncher<ScanOptions> barcodeLauncher = registerForActivityResult(new ScanContract(), result -> {
        if (result.getContents() == null) {
            // Toast.makeText(ScanCodeDeliveryActivity.this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            LogUtils.d(result.getContents());
        }
    });


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.fl_scan) {
            ScanOptions options = new ScanOptions();
            options.setDesiredBarcodeFormats(ScanOptions.QR_CODE);
            options.setOrientationLocked(false);
            options.setPrompt("请将二维码置于取景框内扫描");
            barcodeLauncher.launch(options);
        } else if (view.getId() == R.id.tv_Invitation_code) {
            mTvSpecialCode.setBackground(null);
            mTvSpecialCode.setTextColor(Color.parseColor("#000000"));
            mTvInvitationCode.setBackgroundResource(R.drawable.bg_code_checked);
            mTvInvitationCode.setTextColor(Color.parseColor("#FFFFFF"));
        } else if (view.getId() == R.id.tv_special_code) {
            mTvInvitationCode.setBackground(null);
            mTvInvitationCode.setTextColor(Color.parseColor("#000000"));
            mTvSpecialCode.setBackgroundResource(R.drawable.bg_code_checked);
            mTvSpecialCode.setTextColor(Color.parseColor("#FFFFFF"));
        } else if (view.getId() == R.id.tv_save) {
            // 获取图片某布局
            mFlCode.setDrawingCacheEnabled(true);
            mFlCode.buildDrawingCache();
            methodRequiresTwoPermission();
        } else if (view.getId() == R.id.tv_share) {
            if (type == 1) {
                // 获取图片某布局
                mFlCode.setDrawingCacheEnabled(true);
                mFlCode.buildDrawingCache();
                WxShareUtils.shareBmp(mActivity, mFlCode.getDrawingCache());
                mFlCode.setDrawingCacheEnabled(false);
            } else {
                bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.logo5);
                WxShareUtils.shareWeb(mActivity, content, "邀请下载", "新人注册领取大额红包", bmp);
            }
        } else if (view.getId() == R.id.tv_more) {
            AttachMoreDialog2 attachMoreDialog = new AttachMoreDialog2(mActivity,mList);
            new XPopup.Builder(mActivity).isTouchThrough(true).isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .atView(mTvMore).hasShadowBg(false) // 去掉半透明背景
                    .asCustom(attachMoreDialog).show();
            attachMoreDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    if (id.equals("打印标签")) {
                        if (TextUtils.isEmpty(bluetoothAddress)) {
                            ToastUtil.show("请先配置打印机");
                            return;
                        }
                        attachMoreDialog.dismiss();
                        loadingPopupShow();
                        bluetoothPermission();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                loadingPopupDismiss();
                            }
                        }, 1000);
                    } else if (id.equals("配置打印机")) {
                        startActivity(new Intent(mActivity, BluetoothConfigurationActivity.class));
                    }
                }
            });
        }
    }


    private void bluetoothPermission() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (ContextCompat.checkSelfPermission(ScanCodeDeliveryActivity.this, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_DENIED) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        ActivityCompat.requestPermissions(ScanCodeDeliveryActivity.this, new String[]{Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN}, 2);
                    } else {
                        print();
                    }
                } else {
                    print();
                }

            }
        }).start();

    }

    private void print() {
        if (!myBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            startActivityForResult(enableBtIntent, 2);
        }

        zpBluetoothPrinter zpSDK = new zpBluetoothPrinter(this);
        if (!zpSDK.connect(bluetoothAddress)) {
            ToastUtil.show("连接失败");
            return;
        }

        int marginTop = 20;
        zpSDK.pageSetup(600, 500);
        zpSDK.drawText(168, marginTop, "扫一扫发货/取货", 3, 0, 0, false, false);
        // zpSDK.drawGraphic(90, marginTop, 100, 100, bmp);
        marginTop = marginTop + 60;
        zpSDK.drawQrCode(160, marginTop, content, 0, 5, 0);
        marginTop = marginTop + 300;
        int textLeft = (18 - company_name.length()) * 16;
        zpSDK.drawText(textLeft, marginTop, company_name, 3, 0, 0, false, false);
        zpSDK.print(0, 0);

        zpSDK.printerStatus();
        int a = zpSDK.GetStatus();

        if (a == -1) { //"获取状态异常------";
            ToastUtil.show("获取状态异常");
        }
        if (a == 1) {//"缺纸----------";
            ToastUtil.show("缺纸");
        }
        if (a == 2) {
            //"开盖----------";
            ToastUtil.show("开盖");
        }
        if (a == 0) {
            ToastUtil.show("打印机正常");
            //"打印机正常-------";
        }

        zpSDK.disconnect();
    }

    public static final int RC_LOCATION = 1; // requestCode
    public static final int RC_BLUETOOTH = 2; // requestCode
    String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            MediaStoreUtils.saveImages(mActivity, mFlCode.getDrawingCache());
            mFlCode.setDrawingCacheEnabled(false);
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "我需要权限来保存图片", RC_LOCATION, perms);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFlCode.destroyDrawingCache();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("提示").setRationale("此功能需要开通权限，请转到设置打开权限").build().show();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        bluetoothAddress = SharedPreferencesUtils.getString(mActivity, "bluetoothAddress");
    }
}